package club.weiyuanstudio.android.app.message_station.api

import android.os.StrictMode
import android.util.Log
import club.weiyuanstudio.android.app.message_station.api.data.Message
import com.google.gson.Gson
import okhttp3.MediaType.Companion.toMediaType
import okhttp3.OkHttpClient
import okhttp3.Request
import okhttp3.RequestBody
import java.util.*


class MessageStationAPI {
    init {
        val policy =
            StrictMode.ThreadPolicy.Builder().permitAll().build()
        StrictMode.setThreadPolicy(policy)
    }

    private val _CLENT = OkHttpClient()
    private val _JSON_TYPE = "application/json; charset=utf-8".toMediaType()

    fun getMessageList(): Array<Message> {
        val request = Request.Builder()
            .url("https://message-station.weiyuanstudio.club/release/message")
            .header("Token", "TEST")
            .build()

        val jsonString = _CLENT.newCall(request).execute().body?.string()

        Log.d("TAG", jsonString!!)

        return Gson().fromJson(jsonString, Array<Message>::class.java)
    }

    fun saveMessage(message: Message) {
        Log.d(javaClass.name, "saveMessage: $message")

        val json = Gson().toJson(message).encodeToByteArray()

        val req = RequestBody.create(_JSON_TYPE, json)
        val request = Request.Builder()
            .url("https://message-station.weiyuanstudio.club/release/message")
            .header("Token", "TEST")
            .post(req)
            .build()

        val jsonString = _CLENT.newCall(request).execute().body?.string()
        Log.d(javaClass.name, "saveMessage Success $jsonString")
    }
}
